package com.lyEducation.repositoryImpl.base;

import com.lyEducation.core.base.ResponseCodeConstans;
import com.lyEducation.core.base.TokenConstants;
import com.lyEducation.core.base.ValidationUtils;
import com.lyEducation.entities.base.BaseDataEntity;
import com.lyEducation.repository.base.BaseDateRepository;
import com.lyEducation.security.config.SecurityPrincipalContext;
import com.lyEducation.util.StringUtils;
import com.lyEducation.util.controllerUtil.JsonResult;

import java.sql.Timestamp;
import java.util.List;

public abstract class BaseDateRepositoryImpl<X extends BaseDataEntity> extends BaseRepositoryImpl<X>
    implements BaseDateRepository<X> {

  @Override
  public X save(X entity) {
    Timestamp timeByCreateOrUpd = new Timestamp(System.currentTimeMillis());
    setCreateParam(entity, timeByCreateOrUpd);
    setUpdParam(entity, timeByCreateOrUpd);
    super.save(entity);
    return entity;
  }

  @Override
  public X update(X entity) {
    setUpdParam(entity, new Timestamp(System.currentTimeMillis()));
    return super.update(entity);
  }

  @Override
  public JsonResult batchObject(List<X> entityList) {
    for (X entity : entityList) {
      String isVali = ValidationUtils.validation(entity);
      if (!isVali.equals(ResponseCodeConstans.SUCCESS)) {
        return JsonResult.putFail(isVali);
      }
      Timestamp timestamp = new Timestamp(System.currentTimeMillis());
      if (StringUtils.isBlank(entity.getId())) {
        setCreateParam(entity, timestamp);
        entityManager.persist(entity);
      } else {
        setUpdParam(entity, timestamp);
        entityManager.merge(entity);
      }
    }
    return JsonResult.putSuccess();
  }

  private void setCreateParam(X entity, Timestamp createTime) {
    entity.setId(TokenConstants.generateUserId());
    if (SecurityPrincipalContext.getUserDetailsImpl() != null) {
      entity.setCreateId(SecurityPrincipalContext.getUserDetailsImpl().getId());
    }
    entity.setCreateTime(createTime);
    entity.setIsDelete(false);
    entity.setStatus(1);
    entity.setVersion(0);
  }

  private void setUpdParam(X entity, Timestamp updTime) {
    if (SecurityPrincipalContext.getUserDetailsImpl() != null) {
      entity.setUpdateId(SecurityPrincipalContext.getUserDetailsImpl().getId());
    }
    entity.setUpdateTime(updTime);
  }
}
